import requests
import json
import time
import pandas as pd

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69'
}


def main():
    df = pd.read_csv('../static/data/typhoon_list.csv')
    typhoon_id_list = df['id'].values.tolist()
    typhoon_info_list = []
    for typhoon_id in typhoon_id_list:
        typhoon_info_list += [[typhoon_id] + i for i in get_typhoon_info(typhoon_id)]
        print(f'{typhoon_id} 完成')
        time.sleep(2)
    df = pd.DataFrame(typhoon_info_list, columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'])
    df.to_csv('../static/data/typhoon_info.csv', index=False)


def get_typhoon_list():
    typhoon_list = []
    for i in range(13, 24):
        url = f'http://typhoon.nmc.cn/weatherservice/typhoon/jsons/list_20{i}'
        params = {
            't': int(time.time() * 1000),
            'callback': f'typhoon_jsons_list_20{i}'
        }
        print(url)
        response = requests.get(url, headers=headers, params=params)
        data = json.loads(response.text[24:-1])
        typhoon_list += data.get('typhoonList', [])
        time.sleep(2)
    df = pd.DataFrame(typhoon_list, columns=['id', 'eName', 'cName', 'aNumber', 'bNumber', 'cNumber', 'text', 'status'])
    df.to_csv('../static/data/typhoon_list.csv', index=False)


def get_typhoon_info(typhoon_id):
    url = f'http://typhoon.nmc.cn/weatherservice/typhoon/jsons/view_{typhoon_id}'
    params = {
        't': int(time.time() * 1000),
        'callback': f'typhoon_jsons_view_{typhoon_id}'
    }
    try:
        response = requests.get(url, headers=headers, params=params)
        data = json.loads(response.text[len(f'typhoon_jsons_view_{typhoon_id}('):-1])
        return data.get('typhoon', [])[8]
    except:
        print(f'{typhoon_id}获取失败,重新请求')
        return get_typhoon_info(typhoon_id)


if __name__ == '__main__':
    main()
